import {Component, OnInit} from '@angular/core';
import {HomeService} from './home.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {

  constructor(private homeService: HomeService) {
  }

  selectedValue = null;
  listOfOption: Array<{ value: string; text: string }> = [];
  name: string;
  tabList = [
    {name: '政策矩阵', router:'/home', active: true},
    {name: '政策文件', router:'/magic-science-innovate', active: false},
    {name: '政策专题', router:'/policy-analysis-matrix', active: false},
    {name: '计量分析', router:'/policy-analysis-chart', active: false},
  ];
  nzFilterOption = () => true;

  ngOnInit(): void {
  }

  search(inputValue: string) {
    this.homeService.getPreKey(inputValue).subscribe(res => {
      const listOfOption: Array<{ value: string; text: string }> = [];
      if (res.result.length) {
        // 如果当前搜索的词, 非后台关键词。则把它放在第一个展示。
        if (inputValue !== '' && res.result.indexOf(inputValue) === -1) {
          listOfOption.push({
            value: inputValue,
            text: inputValue
          });
        }
        res.result.forEach(item => {
          listOfOption.push({
            value: item,
            text: item
          });
        });
      } else {
        listOfOption.push({
          value: inputValue,
          text: inputValue
        });
      }
      this.listOfOption = listOfOption;
    });
  }

  // 首次点击时, 出的默认推荐。nz-select默认有此功能, nz-autocomplete需要单独支持。
  clickInput() {
    if (!this.selectedValue && this.listOfOption.length === 0) {
      this.search('');
    }
  }

  getName(name: string) {
    this.name = name;
  }

  clickTab(index: number) {
    for (const tab of this.tabList) {
      tab.active = false;
    }
    this.tabList[index].active = true;
  }
}
